package org.hit.burkun.index.term;

import java.util.Collection;
import java.util.LinkedList;

import org.hit.burkun.db.DBHelper;
import org.hit.burkun.db.DBTypeConverter;
import org.hit.burkun.db.DBTypeConverter.DATATYPE;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class IndexTermDump {

	private DBHelper dbh;
	private String[] insertFileds = { "db_id", "ent_name", "ent_dec",
			"ent_url", "ent_type", "ent_cuis", "source_table" };
	private DBTypeConverter dataTypesCovert;
	private String tbName;
	/*
	 * CREATE TABLE `index_term` ( `db_id` int(11) DEFAULT NULL COMMENT 'db_id
	 * may gene id, go acc, uniport kb ac ', `ent_name` varchar(200) DEFAULT
	 * NULL, `ent_dec` text, `ent_url` varchar(512) DEFAULT NULL, `ent_type`
	 * varchar(50) DEFAULT NULL, `ent_cuis` text, `source_table` varchar(255)
	 * DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
	 */
	private static Logger logger = LoggerFactory.getLogger(IndexTermDump.class);

	public IndexTermDump(DBHelper dbh, String tbName) {
		this.dbh = dbh.clone();
		this.tbName = tbName;

		DATATYPE[] dataTypes = new DATATYPE[insertFileds.length];

		dataTypesCovert = new DBTypeConverter(dataTypes);
	}

	public void saveToTable(Collection<IndexTerm> data) {
		/*
		 * CREATE TABLE `index_term` ( `db_id` varchar(55) DEFAULT NULL COMMENT
		 * 'db_id may gene id, go acc, uniport kb ac ', `ent_name` varchar(200)
		 * DEFAULT NULL, `ent_dec` text, `ent_url` varchar(512) DEFAULT NULL,
		 * `ent_type` varchar(50) DEFAULT NULL, `ent_cuis` text, `source_table`
		 * varchar(255) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
		 */
		logger.debug("save term data in to " + tbName + "...");
		LinkedList<String[]> insertData = new LinkedList<>();
		// 加一个判断，
		for (IndexTerm term : data) {
			String[] line = new String[insertFileds.length]; // 忽略primary id
			line[0] = term.getEntity().getDbid();
			line[1] = term.getEntity().getName();
			line[2] = term.getEntity().getDef();
			line[3] = term.getUrl();
			line[4] = term.getEntity().getType().getTag();
			line[5] = term.getEntity().getUid();
			line[6] = term.getFormTbName();
			insertData.add(line);
		}
		dbh.connectionDB();
		dbh.insertBatch(tbName, insertFileds, insertData, dataTypesCovert);
		dbh.disconnection();
		logger.debug("save term data in to " + tbName + " done!");
	}
}
